import api from '@/api';
import {encrypt} from '@/utils/crypto';
import identityAsideMenu from '@/config/asideMenu';
import homeChildren from '@/router/home.children.js';

//过滤视图
function filterView(name){  //身份信息  admin  consumer
    return identityAsideMenu.filter(item => item.identity.includes(name)).map(val => {
        val.children = val.children.filter(item => {
            return item.identity.includes(name)
        })
        return val
    })
}

function format(data){  //视图data
    return data.map(item => {
        item.children = item.children.map(val => {
            let {path,meta} = homeChildren.find(v => v.name === val.name);
            return {
                ...val,
                path,
                meta
            }
        })
        return item
    })
}


export default {
    state:{
        userinfo:{},
        asideMenu:[]
    },
    actions:{
        //登录
        async login(context,payload){
            let res = await api.login(payload);
            localStorage.setItem('token',res.data.token);
            return {code:1,msg:'登录成功'}
        },
        //获取用户信息
        async getUserInfo({commit}){
            let info = await api.getUserInfo();
            localStorage.setItem('userinfo',encrypt(JSON.stringify(info.data)));
            commit('SET_USERINFO',info.data);
        }
    },
    mutations:{
        SET_USERINFO(state,payload){
            state.userinfo = payload;
            
            state.asideMenu = format(filterView(payload.identity.name));
            console.log(state.asideMenu)
            
        }
    },
    getters:{

    },
    namespaced:true
}